import common.helper_tradetime as helper_tradetime
import threading
import time
import datetime as dt
import common.helper_utils as util
import common.helper_log as common_log
import common.helper_ding as ding
import multiprocessing
import common.constants as const
import services.service_hq as hq


_timer = helper_tradetime.TradetimeHelper()
_log = common_log.LogHelper()
_alert = ding.DingHelper()
_hq_service = hq.HqService()

def execute_for_once():

    # msg ="【service_start】 [execute_for_once] get_kline_day_all_for_once  Begin"
    # _log.log_info(msg)
    # _hq_service.get_kline_day_all_for_once()
    # msg ="【service_start】[execute_for_once] get_kline_day_all_for_once End...."
    # _log.log_info(msg)
    

    msg ="【service_start】 [execute_for_once] get_kline_day_currentday Begin"
    _log.log_info(msg)
    df = _hq_service.get_kline_day_currentday()

    if df is not None:
        for row in df.iterrows():
            hqmsg = f"{row[1]['ts_code']},o:{row[1]['open']},h:{row[1]['high']},l:{row[1]['low']},c:{row[1]['close']},v:{row[1]['vol']}"
            _log.log_info(hqmsg)
            _alert.send_msg(hqmsg) 
    else:
        _log.log_error("execute_for_once 没有获取到数据")
                
    msg ="【service_start】 [execute_for_once] get_kline_day_currentday  End....."
    _log.log_info(msg)
       

def start_thread():
    """service_start.py
    启动一个线程
    :param target: 线程执行的函数
    :param args: 线程执行函数的参数
    :return: 线程对象
    """

    errorCount = 0
    child_process = None
    trading = False

    msg ="【service_start】 progress start"
    _log.log_info(msg)
    _alert.send_msg(msg)


    child_process = multiprocessing.Process(target=execute_for_once)
    child_process.start()
            

    _log.log_info("【service_start】exceuted once.Start while loop")

    
    while True:
        try:
            if(_timer.is_trade_day() and _timer.is_trade_life_time()):
                trading = True
            else:
                trading = False
                
            if(_timer.is_end_of_day()):  # 结束交易日，退出子进程
                _log.log_info("【EndOfDay】 获取当日交易数据。")
                df = _hq_service.get_kline_day_currentday()
                
                if df is not None:
                    for row in df.iterrows():
                        hqmsg = f"{row[1]['ts_code']},o:{row[1]['open']},h:{row[1]['high']},l:{row[1]['low']},c:{row[1]['close']},v:{row[1]['vol']}"
                        _log.log_info(hqmsg)
                        _alert.send_msg(hqmsg) 
                    _log.log_info("【EndOfDay】 处理完毕<success>。休息15分钟")
                    time.sleep(60 * 15)
                else:
                    _log.log_error("【EndOfDay】 没有获取到数据")
                
            # Start child process in trading period
            if trading and child_process is None:
                pass
            # if trading and child_process is None:
            #     _log.log_info("启动进程: hq_service")
            #     child_process = multiprocessing.Process(target=_hq_service.get_kline_day_currentday)
            #     child_process.start()
               

            # # 非记录时间则退出子进程
            # if not trading and child_process is not None:
            #     _log.log_info("关闭子进程")
            #     # child_process.terminate()
            #     # child_process.join()
            #     child_process = None
            #     _log.log_info("子进程关闭成功", True)
            #     _alert.send_msg("【close】 child process")

            # time.sleep(10)
            errorCount = 0
        except Exception as ex:
            _log.log_error(f"【service_start】[start_thread]异常：{str(ex)},{errorCount}")
            errorCount = errorCount +1
            time.sleep(3)
            if(errorCount > 5):
                _log.log_error(f"【service_start】[start_thread]连续出错5次，退出程序")
                break
                # multiprocessing.terminate()            
        finally:            
            if(util.random_rate):
                _log.log_info("running......")
                
            time.sleep(60 * 5)

